package cn.tyoui.sbo;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class SBO {
    private final String INDEX = "http://www.bigdata-expo.org/";
    private final String URL = INDEX + "exhibitor/listing";
    private final String labelClass = "nub-x";
    private final String urlClass = "exhibitor-listing-img-container";
    private final String nameClass = "company-name";
    private final String messageTag = "p";

    public List<SBOBean> getMessage() throws IOException {
        List<SBOBean> list = new ArrayList<>();
        Document document = Jsoup.connect(URL).get();
        Elements elements = document.getElementsByTag("tr");
        for (int i = 1; i < elements.size(); i++) {
            Element element = elements.get(i);
            String label = element.getElementsByClass(labelClass).text();
            String url = element.getElementsByClass(urlClass).get(0).getElementsByTag("img").attr("src");
            System.out.println(url);
            Elements es = element.getElementsByClass(nameClass);
            String nameURL = es.get(0).getElementsByTag("a").attr("href");
            String name = es.get(0).text();
            Document documents = Jsoup.connect(INDEX + nameURL).get();
            String message = documents.getElementsByTag(messageTag).text();
            SBOBean sboBean = new SBOBean(label, url, name, message);
            list.add(sboBean);
            documents.clone();
        }
        return list;
    }

    public void writerMessage(List<SBOBean> list, String messagePath, String photoPathDIC) throws Exception {
        Writer writer = new FileWriter(messagePath);
        for (SBOBean sboBean : list) {
            writer.write(sboBean.toString());
            writer.flush();
            if (sboBean.getUrl().length() > 1)
                download(sboBean.getUrl(), sboBean.getName()+".jpg", photoPathDIC);
        }
        writer.close();
    }

    private static void download(String urlString, String filename, String savePath) throws Exception {
        URL url = new URL(urlString);
        URLConnection con = url.openConnection();
        con.setConnectTimeout(5 * 1000);
        InputStream is = con.getInputStream();
        byte[] bs = new byte[1024];
        int len;
        File sf = new File(savePath);
        OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        is.close();
    }
}
